<template>
	<view class="content">
		<view id="nav-bar" class="nav-bar">
			<view v-for="(item,index) in tabBars" :key="item.value" class="nav-item"
				:class="{current: index === tabCurrentIndex}" :id="'tab'+index" @click="changeTab(index)">
				{{item.name}}
			</view>
		</view>
		<swiper id="swiper" class="swiper-box" :duration="300" :current="tabCurrentIndex" @change="changeTab">
			<swiper-item v-for="tabItem in tabBars" :key="tabItem.value">
				<scroll-view class="panel-scroll-box" scroll-with-animation scroll-y
					@scrolltolower="loadMore(cateId,tabItem)">
					<resource-list :resourceList="tabItem.resourceList" :cols="1"></resource-list>
					<uni-load-more :status="tabItem.loadMoreStatus"></uni-load-more>
				</scroll-view>
			</swiper-item>
		</swiper>

	</view>
</template>

<script>
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue'
	import resourceList from '@/components/resource-list.vue'
	let windowWidth = 0,scrollTimer = false,tabBar;
	export default {
		components: {
			resourceList,
			uniLoadMore
		},
		data() {
			return {
				headerPosition:"fixed",
				headerTop:"0px",
				cateId: '', //资源类目(页面参数传入)
				tabBars: [{
					name: '全部',
					value: '0',
					loadMoreStatus: 'more',
					pageNo: 1,
					resourceList: [],
					loaded: false

				},{
					name: '文章',
					value: '1',
					loadMoreStatus: 'more',
					pageNo: 1,
					resourceList: [],
					loaded: false

				}, {
					name: '音频',
					value: '2',
					loadMoreStatus: 'more',
					pageNo: 1,
					resourceList: [],
					loaded: false
				}, {
					name: '视频',
					value: '3',
					loadMoreStatus: 'more',
					pageNo: 1,
					resourceList: [],
					loaded: false
				}, {
					name: '电子书',
					value: '4',
					loadMoreStatus: 'more',
					pageNo: 1,
					resourceList: [],
					loaded: false
				}],
				tabCurrentIndex: 0, //当前选项卡索引
				pageSize: 5,
				pageNo: 1
			};
		},

		onLoad(options) {
			// #ifdef H5
			this.headerTop = document.querySelector(".uni-page-head").offsetHeight + 'px';
			// #endif
			this.cateId = options.cateId;	//资源类目
			this.tagName = options.tagName;	//标签名称
			this.searchKey = options.searchKey;	//资源名称

			let tabItem = this.tabBars[this.tabCurrentIndex];
			this.loadResource(this.cateId, tabItem);
		},
		onPageScroll(e) {
			//兼容iOS端下拉时顶部漂移
			if (e.scrollTop >= 0) {
				this.headerPosition = "fixed";
			} else {
				this.headerPosition = "absolute";
			}
		},
		//下拉刷新
		onPullDownRefresh() {
			//重新加载数据
			this.resetPage();
		},
		//加载更多
		onReachBottom() {
			if (this.loadingType === 'more') {
				this.pageNo = this.pageNo + 1;
			}
		},
		methods: {
			//分页查询资源
			prepareSearchResource(cateId, tabItem) {
				tabItem.loadMoreStatus = 'loading';
				var keyArray = [];
				keyArray.push('IS_PUBLISHED');
				if (cateId)
					keyArray.push('RESOURCE_CATE');
				if (this.searchKey)
					keyArray.push('RESOURCE_NAME');
				if (this.tagName)
					keyArray.push('RESOURCE_TAG_NAME');
				//非全部显示, 指定资源类型查询条件
				if(this.tabCurrentIndex != 0)
					keyArray.push('RESOURCE_TYPE');
				let searchData = {
					'keyArray': keyArray,
					'published': true,
					'resourceCateUuid': cateId,
					'resourceType': tabItem.value,
					'resourceName': this.searchKey,
					'resourceTagName': this.tagName,
					'startIndex': (tabItem.pageNo - 1) * this.pageSize,
					'pageSize': this.pageSize,
				};
				return searchData;
			},
			//加载更多资源
			loadMore(cateId, tabItem) {
				//如果已经加载完成则直接返回
				if (tabItem.loadMoreStatus === 'noMore') {
					return;
				}
				tabItem.pageNo = tabItem.pageNo + 1;
				let searchData = this.prepareSearchResource(cateId, tabItem);
				this.searchResource(searchData, function(resourceList, total) {
					tabItem.resourceList = tabItem.resourceList.concat(resourceList);
					tabItem.loadMoreStatus = tabItem.resourceList.length >= total ? 'noMore' : 'more';
				});

			},
			loadResource(cateId, tabItem) {
				//如果已经加载完成则直接返回
				if (tabItem.loadMoreStatus === 'noMore') {
					return;
				}
				let searchData = this.prepareSearchResource(cateId, tabItem);
				this.searchResource(searchData, function(resourceList, total) {
					tabItem.resourceList = tabItem.resourceList.concat(resourceList);
					tabItem.loadMoreStatus = tabItem.resourceList.length >= total ? 'noMore' : 'more';
				});

			},
			searchResource(searchData, callback) {
				let that = this;
				that.$api.request.searchResource(searchData, res => {
					if (res.body.status.statusCode === '0') {
						let total = res.body.data.total;
						let resourceList = res.body.data.resourceList;
						callback(resourceList, total);
					} else {
						console.log(res.body.status.errorDesc);
					}
				}, true);
			},
			//tab切换
			async changeTab(e) {

				if (scrollTimer) {
					//多次切换只执行最后一次
					clearTimeout(scrollTimer);
					scrollTimer = false;
				}
				let index = e;
				//e=number为点击切换，e=object为swiper滑动切换
				if (typeof e === 'object') {
					index = e.detail.current
				}
				if (typeof tabBar !== 'object') {
					tabBar = await this.getElSize("nav-bar")
				}
				//计算宽度相关
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0;
				let nowWidth = 0;
				//获取可滑动总宽度
				for (let i = 0; i <= index; i++) {
					let result = await this.getElSize('tab' + i);
					width += result.width;
					if (i === index) {
						nowWidth = result.width;
					}
				}
				if (typeof e === 'number') {
					//点击切换时先切换再滚动tabbar，避免同时切换视觉错位
					this.tabCurrentIndex = index;
				}
				//延迟300ms,等待swiper动画结束再修改tabbar
				scrollTimer = setTimeout(() => {
					if (width - nowWidth / 2 > windowWidth / 2) {
						//如果当前项越过中心点，将其放在屏幕中心
						this.scrollLeft = width - nowWidth / 2 - windowWidth / 2;
					} else {
						this.scrollLeft = 0;
					}
					if (typeof e === 'object') {
						this.tabCurrentIndex = index;
					}
					this.tabCurrentIndex = index;


					//第一次切换tab，动画结束后需要加载数据
					let tabItem = this.tabBars[this.tabCurrentIndex];
					if (this.tabCurrentIndex !== 0 && tabItem.loaded !== true) {
						this.loadResource(this.cateId, tabItem);
						tabItem.loaded = true;
					}
				}, 300)

			},
			//获得元素的size
			getElSize(id) {
				return new Promise((res, rej) => {
					let el = uni.createSelectorQuery().select('#' + id);
					el.fields({
						size: true,
						scrollOffset: true,
						rect: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
			//详情
			navToDetailPage(item) {
				let id = item.resourceUuid;
				uni.navigateTo({
					url: '/pages/resource/resource-detail?id=' + id
				})
			},
			stopPrevent() {}
		},
	}
</script>

<style lang="scss">
	page{
		background: $bg-color-light;
	}
	.content{
		margin: 0 $page-row-spacing;
	}

	.swiper-box {
		height: 100vh;
	}
	
	.panel-scroll-box {
		height: 100%;
	
		.panel-item {
			background: #fff;
			padding: 30px 0;
			border-bottom: 2px solid #000;
		}
	}
</style>